package com.atguigu.tingshu.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private RabbitService rabbitService;

	@Override
	public BigDecimal getTrackBreakSecond(Long trackId, Long userId) {
		//从MongDB中查询数据
		Query query = Query.query(Criteria.where("trackId").is(trackId));
		//集合名称如何定义
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		if (userListenProcess == null) {
			return new BigDecimal("0.00");
		}
		//返回数据
		return userListenProcess.getBreakSecond();
	}


	@Override
	public void updateListenProcess(UserListenProcessVo userListenProcessVo, Long userId) {
		//用这个实体类UserListenProcess 当做数据载体存储到MongoDB中！
		//从MongDb中查询数据
		Query query = Query.query(Criteria.where("trackId").is(userListenProcessVo.getTrackId()));
		//集合名称如何定义
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		//集合中没有数据,说明是头一次播放该声音
		if(null==userListenProcess){
			//创建对象
			userListenProcess = new UserListenProcess();
			userListenProcess.setUserId(userId);
			userListenProcess.setAlbumId(userListenProcessVo.getAlbumId());
			userListenProcess.setTrackId(userListenProcessVo.getTrackId());
			userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			userListenProcess.setIsShow(1);
			userListenProcess.setCreateTime(new Date());
			userListenProcess.setUpdateTime(new Date());
		}else {
			//不是第一次播放该声音,要覆盖
			userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			//覆盖更新时间
			userListenProcess.setUpdateTime(new Date());
		}
		//保存数据
		mongoTemplate.save(userListenProcess, collectionName);
		//播放完,播放量加一,防止恶意刷播放量,一个用户在同一天有效,第一次播放playNum+1,第二次播放playNUm
		//redis ; setnx key value  当key不存在的时候生效,  key=userId:trackId value=1
		String key = userId + ":" + userListenProcessVo.getTrackId();
		Boolean result = redisTemplate.opsForValue().setIfAbsent(key, 1, 1, TimeUnit.DAYS);
		if (result){
			//发送消息,更新播放量统计
			TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
			trackStatMqVo.setAlbumId(userListenProcessVo.getAlbumId());
			trackStatMqVo.setTrackId(userListenProcessVo.getTrackId());
			//业务编号:防止重复消费
			String businessId = UUID.randomUUID().toString().replaceAll("-", "");
			trackStatMqVo.setBusinessNo(businessId);
			trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
			trackStatMqVo.setCount(1);
			//第一次播放：更新播放量+1; track_stat album_stat 专辑播放量+1;
			rabbitService.sendMessage(MqConst.EXCHANGE_TRACK,MqConst.ROUTING_TRACK_STAT_UPDATE, JSON.toJSONString(trackStatMqVo));
		}
	}

	@Override
	public Map<String, Object> getLatelyTrack(Long userId) {

		//创建map
		Map<String, Object> map = new HashMap<>();
		//最近播放的声音
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		//查询所有数据并按照更新时间进行降序排列获取第一条数据
		Query query = new Query();
		query.with(Sort.by(Sort.Direction.DESC, "updateTime")).limit(1);
		List<UserListenProcess> processList = mongoTemplate.find(query, UserListenProcess.class, collectionName);
		//获取数据
		if (processList.size() > 0){
			map.put("trackId",processList.get(0).getTrackId());
			map.put("albumId",processList.get(0).getAlbumId());
		}
		return map;
	}

}
